<?php
namespace app\manage\controller;
use think\Db;

class PayChannel extends Base
{
    public function index(){
        if(request()->isAjax() || input('?export')){
            $page = input('page');
            $limit = input('limit');
            $plat = input('plat');
            $date = explodeTime(input('date'));
            $channelId = input('channel_id');
            $debug = input('debug');
            $payType = input('pay_type');

            if(!empty($plat)){
                if($plat=='cps'){
                    $whereCps = $this->whereCps($date, $debug, $channelId, $payType);
                    $backCps = $this->selectCps($date, $whereCps, $channelId);
                    $dataPlat = $backCps['dataCps'];
                    $sumPlat = $backCps['sumCps'];
                    $countPlat = count($dataPlat);
                }else{
                    $whereSdk = $this->whereSdk($date, $debug, $channelId);
                    $backSdk = $this->selectSdk($date, $whereSdk, $channelId);
                    $dataPlat = $backSdk['dataSdk'];
                    $sumPlat = $backSdk['sumSdk'];
                    $countPlat = count($dataPlat);
                }
            }else{
                $whereCps = $this->whereCps($date, $debug, $channelId, $payType);
                $whereSdk = $this->whereSdk($date, $debug, $channelId);

                $backCps = $this->selectCps($date, $whereCps, $channelId);
                $backSdk = $this->selectSdk($date, $whereSdk, $channelId);

                $dataPlat = array_merge($backCps['dataCps'], $backSdk['dataSdk']);
                $sumPlat = $backCps['sumCps'] + $backSdk['sumSdk'];
                $countPlat = count($dataPlat);
            }

            $data = [];

            //如果没数据
            if(!$countPlat){
                if(input('?export')){
                    array_unshift($data, ['支付时间', '渠道ID', '渠道名称', '充值金额']);
                    exportExcel($data, input('date').'渠道充值', input('date').'渠道充值');
                }else{
                    $this->layTable();
                }
            }

            //按照金额排序
            $dataSort = $channelId ? arraySequence($dataPlat, 'date_time') : arraySequence($dataPlat, 'total_price');

            if(input('?export')){
                $dataSlice = array_slice($dataSort, 0);
            }else{
                $dataSlice = array_slice($dataSort, ($page-1)*$limit, $limit);
            }

            $channelIdName = model('Channel')->channelIdName();
            foreach ($dataSlice as $k=>$v){
                $data[] = [
                    'daytime' => $channelId ? $v['date_time'] : input('date'),
                    'channel_id' => $v['channel_id'],
                    'channel_name' => isset($channelIdName[$v['channel_id']]) ? $channelIdName[$v['channel_id']] : '',
                    'total_price' => round($v['total_price']/100, 2)
                ];
            }

            if(input('?export')){
                array_unshift($data, ['支付时间', '渠道ID', '渠道名称', '充值金额']);
                exportExcel($data, input('date').'渠道充值', input('date').'渠道充值');
            }

            $this->layTable(0, '渠道充值', $data, $countPlat, round($sumPlat/100, 2));
        }else{
            $date = date('Y-m-d', time()).' - '.date('Y-m-d', time());
            return view('', ['date'=>$date, 'date2'=>'2018-01 - 2018-01']);
        }
    }

    private function whereCps($date, $debug, $channelId, $payType){
        $whereCps = "pay_time between '{$date['start_time']}' AND '{$date['end_time']}' && channel_id='1000' && pay_result='1'";
        $whereCps .= model('manage/Game')->gameClient(input('game_server'), input('game_publish'), input('game_platform'), input('game_client'));

        if(!empty($payType)){
            if($payType == 'wxpay'){
                $whereCps .= " && left(pay_type, 5)='{$payType}'";
            }else{
                $whereCps .= " && left(pay_type, 6)='{$payType}'";
            }
        }

        if(!empty($debug)){
            if($debug == 1){
                $whereCps .= " && debug='{$debug}'";
            }else{
                $whereCps .= " && debug='0'";
            }
        }

        if(!empty($channelId)){
            $allChannelId = model('Channel')->allChannelId($channelId);
            $whereCps .= " && channel_id=1000 && reg_cps_id in ({$allChannelId})";
        }

        return $whereCps;
    }

    private function whereSdk($date, $debug, $channelId){
        $whereSdk = "pay_time between '{$date['start_time']}' AND '{$date['end_time']}' && channel_id>='5000' && pay_result='1'";
        $whereSdk .= model('manage/Game')->gameClient(input('game_server'), input('game_publish'), input('game_platform'), input('game_client'));

        if(!empty($debug)){
            if($debug == 1){
                $whereSdk .= " && debug='{$debug}'";
            }else{
                $whereSdk .= " && debug='0'";
            }
        }

        if( !empty($channelId) ){
            $whereSdk .= " && channel_id='{$channelId}'";
        }

        return $whereSdk;
    }

    private function selectCps($date, $whereCps, $channelId){
        $y1 = date('Y', $date['start_time']);
        $y2 = date('Y', $date['end_time']);

        //按天分组
        if($channelId){
            $fieldChannel = "reg_cps_id as channel_id, sum(total_price) as total_price, FROM_UNIXTIME(pay_time, '%Y-%m-%d') as date_time";
            $groupChannel = 'reg_cps_id, date_time';
        }else{
            $fieldChannel = 'reg_cps_id as channel_id, sum(total_price) as total_price';
            $groupChannel = 'reg_cps_id';
        }

        if($y1 == $y2){ //同一年
            $selectCps = Db::name('PayOrderY_'.$y1)
                ->field($fieldChannel)
                ->where($whereCps)
                ->group($groupChannel)
                ->select();

            $sumCps = Db::name('PayOrderY_'.$y1)
                ->where($whereCps)
                ->sum('total_price');
        }else{ //跨年
            $fieldCps = "reg_cps_id, total_price, pay_time";
            $queryCps = Db::name('PayOrderY_'.$y1)
                ->field($fieldCps)
                ->where($whereCps)
                ->union("select {$fieldCps} from sdk_pay_order_y_{$y2} where ({$whereCps})", true)
                ->buildSql();

            $selectCps = Db::table($queryCps.' y')
                ->field($fieldChannel)
                ->group($groupChannel)
                ->select();

            $sumCps = Db::table($queryCps.' y')
                ->sum('total_price');
        }

        //如果是CPS，二级规划到一级
        $channelIdPid = changeValKey('Channel', 'cps_id', 'pid', 'channel_id=1000');
        foreach($selectCps as $k=>&$v){
            $pid = isset($channelIdPid[$v['channel_id']]) ? $channelIdPid[$v['channel_id']] : '';
            $pid!=0 && $v['channel_id'] = $pid;
        }

        $resultCps = [];
        foreach($selectCps as $val){
            if($channelId){
                $key1 = $val['channel_id'];
                $key2 = $val['date_time'];
                if(!isset($resultCps[$key1][$key2])){
                    $resultCps[$key1][$key2] = $val;
                }else{
                    $resultCps[$key1][$key2]['total_price'] += $val['total_price'];
                }
            }else{
                $key = $val['channel_id'];
                if(!isset($resultCps[$key])){
                    $resultCps[$key] = $val;
                }else{
                    $resultCps[$key]['total_price'] += $val['total_price'];
                }
            }
        }

        $selectCpsTow = [];
        if($channelId){
            foreach($resultCps as $value){
                foreach($value as $v){
                    $selectCpsTow[] = $v;
                }
            }
        }else{
            $selectCpsTow = array_values($resultCps);
        }

        return ['dataCps'=>$selectCpsTow, 'sumCps'=>$sumCps];
    }

    private function selectSdk($date, $whereSdk, $channelId){
        $y1 = date('Y', $date['start_time']);
        $y2 = date('Y', $date['end_time']);

        //按天分组
        if($channelId){
            $fieldChannel = "channel_id, sum(total_price) as total_price, FROM_UNIXTIME(pay_time, '%Y-%m-%d') as date_time";
            $groupChannel = 'channel_id, date_time';
        }else{
            $fieldChannel = 'channel_id, sum(total_price) as total_price';
            $groupChannel = 'channel_id';
        }

        if($y1 == $y2){ //同一年
            $selectSdk = Db::name('PayOrderY_'.$y1)
                ->field($fieldChannel)
                ->where($whereSdk)
                ->group($groupChannel)
                ->select();

            $sumSdk = Db::name('PayOrderY_'.$y1)
                ->where($whereSdk)
                ->sum('total_price');

        }else{ //跨年
            $fieldSdk = "channel_id, total_price, pay_time";
            $querySdk = Db::name('PayOrderY_'.$y1)
                ->field($fieldSdk)
                ->where($whereSdk)
                ->union("select {$fieldSdk} from sdk_pay_order_y_{$y2} where ({$whereSdk})", true)
                ->buildSql();

            $selectSdk = Db::table($querySdk.' y')
                ->field($fieldChannel)
                ->group($groupChannel)
                ->select();

            $sumSdk = Db::table($querySdk.' y')
                ->sum('total_price');
        }

        return ['dataSdk'=>$selectSdk, 'sumSdk'=>$sumSdk];
    }

    private function mySort($arrays,$sort_key,$sort_order=SORT_DESC,$sort_type=SORT_NUMERIC ){
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }
}